package com.tmc.service.intcar;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.intcar.EthAdditionalService;
import com.tmc.bean.intcar.EthCarType;
import com.tmc.bean.intcar.EthPrice;
import com.tmc.bean.intcar.EthQueryPriceReq;
import com.tmc.bean.intcar.EthSubmitOrderReq;
import com.tmc.bean.intcar.EthSubmitOrderResp;
import com.tmc.entity.baseinfo.CarType;
import com.tmc.entity.intcar.IntcarAdditionalService;
import com.tmc.entity.intcar.IntcarOrder;
import com.tmc.entity.intcar.IntcarPassenger;
import com.tmc.service.baseinfo.EthCarTypeServiceImpl;
import com.tmc.service.cache.CacheServiceImpl;
import com.tmc.util.IntcarUtil;
import com.tmc.util.ObjectUtil;
import com.tmc.vendor.intcar.common.ServiceCenter;
import com.tmc.vendor.intcar.common.VendorService;




/**
 * @author zhang
 * @date 2017年12月20日 下午2:23:47 
 */
@Service
public class IntcarSubmitOrderServiceImpl {
	
	@Autowired
	private EthCarTypeServiceImpl carTypeService;
	
	@Autowired
	private CacheServiceImpl cache;
	
	@Autowired
	private IntcarOrderServiceImpl orderService;
	
	private Log log = LogFactory.getLog(this.getClass());
	
	/**
	 * 提交订单
	 * @author zhang
	 * @param context
	 * @param req
	 * @return
	 */
	public CommonResult booking(ContextInfo context, EthSubmitOrderReq req){
		if(ObjectUtil.noText(req.getPriceMark())){
			return CommonResult.makeFail("priceMark不能为空！");
		}
		
		if (req.getPassengers() == null || req.getPassengers().isEmpty()){
			return CommonResult.makeFail("联系人不能为空！");
		}
		
		CommonResult queryPriceReqResult = IntcarUtil.getEthPricingReqFromCache(context, req.getPriceMark(), cache);
		if(!queryPriceReqResult.isSuccess()){
			return queryPriceReqResult;
		}
		//查询价格的条件
		EthQueryPriceReq queryPriceReq = (EthQueryPriceReq) queryPriceReqResult.getObj();
		req.setQueryPriceReq(queryPriceReq); //设置查询价格的条件
		
		//价格列表
		CommonResult cacheResult = IntcarUtil.getPriceFromCache(context, req.getPriceMark(), cache);
		if(!cacheResult.isSuccess()){
			return cacheResult;
		}
		EthPrice price = (EthPrice) cacheResult.getObj();
		
		//检查客户请求价格信息与缓存中的价格信息是否一致
		CommonResult checkResult = this.checkPrice(req, price);
		if(!checkResult.isSuccess()){
			return checkResult;
		}
		
		//根据价格中的供应商向供应商提交订单
		VendorService service = ServiceCenter.getService(price.getVendor());
		EthSubmitOrderResp resp = null;
		try {
			//先保存到本地  获得本地订单ID
			IntcarOrder order = this.buildOrder(context, price, req);
			CommonResult cr = orderService.save(context, order);
			if(!cr.isSuccess()){
				return cr;
			}
			//把订单保存到供应商
			order.setOrderID(order.getOrderID());
			//获取缓存中的车型
			List<CarType> cacheCarTypes = carTypeService.findAllFromCache();
			//把车型ID转为对应供应商的车型ID
			this.changeCarTypeID(req, cacheCarTypes);
			req.setOrderID(order.getOrderID()+"");
			resp = service.submitOrder(context, req);
			if(!resp.isSuccess()){
				// 订单保存到供应商失败
 				orderService.delete(context, order);
				return CommonResult.makeFail(resp.getMessage());
			}
			order.setVendorOrderID(resp.getVendorOrderID());
			orderService.save(context, order);
			return CommonResult.makeSuccess("预定成功！",order.getOrderID());
		} catch (Exception e) {
			log.error("booking出错！", e);
		}
		return CommonResult.makeFail("预定出错！");
	}
	
	/**
	 * 把车型ID转为对应供应商的车型ID
	 * 
	 * @author zhang
	 * @param req
	 * @param cacheCarTypes
	 */
	private void changeCarTypeID(EthSubmitOrderReq req, List<CarType> cacheCarTypes) {
		Integer carTypeID = 0; 
		for (CarType carType : cacheCarTypes) {
			if(carType.getCarTypeID() == req.getCarTypeID()){
				carTypeID = carType.getYitu8CarTypeID();
				break;
			}
		}
		req.setCarTypeID(carTypeID);
	}
	
	/**
	 * 创建订单对象
	 * 
	 * @author zhang
	 * @param context
	 * @param price
	 * @param req
	 * @return
	 */
	private IntcarOrder buildOrder(ContextInfo context, EthPrice price, EthSubmitOrderReq req) {
		
		IntcarOrder order = ObjectUtil.makeTargetBean(req.getQueryPriceReq(), IntcarOrder.class);
		order.setVendor(price.getVendor());
		//order.setVenderOrderID(resp.getVenderOrderID());
		order.setPriceMark(req.getPriceMark());
		order.setStaffNum(req.getStaffNum());
		order.setLuggageNum(req.getLuggageNum());
		order.setCarTypeID(req.getCarTypeID());
		// 用车数量，默认为1
		order.setCarCount(1);
		order.setPassengerList(ObjectUtil.makeTargetList(req.getPassengers(), IntcarPassenger.class));
		order.setAdditionalServiceList(ObjectUtil.makeTargetList(req.getAdditionalServices(), IntcarAdditionalService.class));
		// 设置价格
		order.setTotalAmount(req.getTotalAmount());
		order.setSetAmount(req.getSetAmount());
		order.setAdditionalServiceAmount(req.getAdditionalServiceAmount());
		order.setAddPrice(req.getAddPrice());
		order.setVendorTotalAmount(req.getVendorTotalAmount());
		return order;
	}
	
	/**
	 * 提交订单前验价
	 * @author zhang
	 * @param req
	 * @param price
	 * @return
	 */
	private CommonResult checkPrice(EthSubmitOrderReq req, EthPrice price) {
		double cacheSetAmount = 0d;
		for ( EthCarType carType: price.getCarTypeList()) {
			if(carType.getCarTypeID() == req.getCarTypeID()){
				//套餐费
				//req.setSetAmount(carType.getSetPrice());
				cacheSetAmount = carType.getSetPrice();
				break;
			}
		}
		if(cacheSetAmount != (req.getSetAmount() == null ? 0 : req.getSetAmount()) ){
			return CommonResult.makeFail("套餐价格不一致！");
		}
		double cacheAdditionalServiceAmount = 0d;
		if(req.getAdditionalServices() != null && !req.getAdditionalServices().isEmpty()){
			//有附加服务费
			for (EthAdditionalService reqService : req.getAdditionalServices()) {
				for (EthAdditionalService cacheService : price.getAdditionalServiceList()) {
					if(reqService.getSid().equals(cacheService.getSid())){
						cacheAdditionalServiceAmount += cacheService.getPrice() * ( reqService.getNumber() == null ? 1 : reqService.getNumber());
					} 
				}
			}
		}
		if(cacheAdditionalServiceAmount != (req.getAdditionalServiceAmount() == null ? 0 : req.getAdditionalServiceAmount())){
			return CommonResult.makeFail("套餐价格不一致！");
		}
		req.setVendorTotalAmount(cacheSetAmount + cacheAdditionalServiceAmount);
		if(price.getAddPrice() != (req.getTotalAmount() - req.getVendorTotalAmount())){
			return CommonResult.makeFail("本地加价不一致！");
		}
		req.setAddPrice(price.getAddPrice());
		//计算价格信息
		return CommonResult.makeSuccess();
	}
}
